from flask import Flask, jsonify, render_template, request
from Lift.lift import Lift
import serial
import logging
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler
import os
import traceback

app = Flask(__name__)

# 创建logs目录（如果不存在）
log_dir = os.path.join(os.path.dirname(__file__), 'logs')
os.makedirs(log_dir, exist_ok=True)

# 配置日志记录器
logger = logging.getLogger('lift_api')
logger.setLevel(logging.DEBUG)

# 日志格式
log_formatter = logging.Formatter(
    '%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(funcName)s - %(message)s'
)

# 控制台处理器（INFO级别）
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(log_formatter)

# 文件处理器（按时间切割，每天午夜）
time_rotating_handler = TimedRotatingFileHandler(
    os.path.join(log_dir, 'app.log'),
    when='midnight',
    interval=1,
    backupCount=30,
    encoding='utf-8'
)
time_rotating_handler.setLevel(logging.DEBUG)
time_rotating_handler.setFormatter(log_formatter)

# 文件处理器（按大小切割，20MB）
size_rotating_handler = RotatingFileHandler(
    os.path.join(log_dir, 'app.log'),
    maxBytes=20*1024*1024,  # 20MB
    backupCount=30,
    encoding='utf-8'
)
size_rotating_handler.setLevel(logging.DEBUG)
size_rotating_handler.setFormatter(log_formatter)

# 添加处理器到日志记录器
logger.addHandler(console_handler)
logger.addHandler(time_rotating_handler)
logger.addHandler(size_rotating_handler)

# Configuration
SERIAL_PORT = '/dev/ttyUSB0'  # Replace with actual serial port
BAUDRATE = 9600
lift = None  # Initialize as None

try:
    # Initialize the Lift instance with logging
    logger.info(f"Attempting to connect to lift on {SERIAL_PORT} at {BAUDRATE} baud")
    lift = Lift(port=SERIAL_PORT, baudrate=BAUDRATE)
    logger.info("Lift connection established successfully")
except serial.SerialException as e:
    logger.error(f"Serial connection error: {e}")
    logger.info("Running in simulation mode (no hardware connected)")
except Exception as e:
    logger.error(f"Unexpected error initializing Lift: {e}\n{traceback.format_exc()}")
    logger.info("Running in simulation mode")

@app.route('/')
def index():
    logger.info("Serving index page")
    return render_template('index.html', lift_initialized=(lift is not None))

@app.route('/api/lift/status', methods=['GET'])
def lift_status():
    """Check lift connection status"""
    logger.debug("Received lift status request")
    
    if lift is None:
        logger.error("Lift status check failed: Lift not initialized")
        return jsonify({
            'status': 'error',
            'message': 'Lift not initialized',
            'connected': False
        }), 503
    
    try:
        # Simple check if serial connection is open
        connected = lift.serial_connection.is_open
        logger.info(f"Lift status check successful. Connected: {connected}")
        return jsonify({
            'status': 'success',
            'message': 'Lift is connected' if connected else 'Lift is disconnected',
            'connected': connected
        })
    except Exception as e:
        logger.error(f"Error checking lift status: {e}\n{traceback.format_exc()}")
        return jsonify({
            'status': 'error',
            'message': str(e),
            'connected': False
        }), 500

@app.route('/api/lift/<command>', methods=['POST'])
def lift_command(command):
    logger.debug(f"Received lift command: {command}")
    try:
        if command == 'move_to_position_one':
            logger.info("Moving lift to position one")
            lift.move_to_position_one()
        elif command == 'move_to_position_two':
            logger.info("Moving lift to position two")
            lift.move_to_position_two()
        elif command == 'move_to_position_three':
            logger.info("Moving lift to position three")
            lift.move_to_position_three()
        elif command == 'move_up':
            logger.info("Moving lift up")
            lift.move_up()
        elif command == 'move_down':
            logger.info("Moving lift down")
            lift.move_down()
        elif command == 'reset':
            logger.info("Resetting lift")
            lift.reset()
        elif command == 'stop_moving_up':
            logger.info("Stopping lift moving up")
            lift.stop_moving_up()
        elif command == 'stop_moving_down':
            logger.info("Stopping lift moving down")
            lift.stop_moving_down()
        else:
            logger.error(f"Invalid command received: {command}")
            return jsonify({'error': 'Invalid command'}), 400

        logger.info(f"Command '{command}' executed successfully")
        return jsonify({'status': 'success', 'command': command})
    except Exception as e:
        logger.error(f"Error executing command '{command}': {e}\n{traceback.format_exc()}")
        return jsonify({'error': str(e)}), 500

# 程序启动时的日志
logger.info("Application startup configuration complete")

if __name__ == '__main__':
    logger.info("Starting Lift API server...")
    app.run(host='0.0.0.0', port=5057, debug=True)
